/****************************************
 * 2018 - 2021 版权所有 CopyRight(c) 快程乐码信息科技有限公司所有, 未经授权，不得复制、转发
 */

package com.kclm.security03.config.security.login;

import com.kclm.security03.modules.common.dto.output.ApiResult;
import com.kclm.security03.modules.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/******************
 * @Author yejf
 * @Version v1.0
 * @Create 2020-08-05 21:42
 * @Description 管理员认证失败处理器
 */
@Slf4j
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {

    public AdminAuthenticationFailureHandler() {
        log.debug("创建AdminAuthenticationFailureHandler 对象....");
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {
        log.debug("当认证失败后执行此方法:");
        log.debug("\t请求的url是："+request.getRequestURL());
        ApiResult result;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            log.error("用户名不存在或无效的凭证: "+e.getMessage());
            result = ApiResult.fail(e.getMessage());
        } else if (e instanceof LockedException) {
            log.error("帐户被锁定: "+e.getMessage());
            result = ApiResult.fail("账户被锁定，请联系管理员!");
        } else if (e instanceof CredentialsExpiredException) {
            log.error("凭证过期："+e.getMessage());
            result = ApiResult.fail("证书过期，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            log.error("帐户过期："+e.getMessage());
            result = ApiResult.fail("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            log.error("帐户禁用："+e.getMessage());
            result = ApiResult.fail("账户被禁用，请联系管理员!");
        } else {
            log.error("登录失败：", e);
            result = ApiResult.fail("登录失败!");
        }
        ResponseUtil.out(response, result);
    }
}
